
<template>
  <div style="margin-bottom: 10px">
    <t-button variant="text" theme="primary"  @click="isDialogDevice = true">
      <span style="color: #fff">当前套餐视频频模板数：{{memberInfo.videos}}/{{memberInfo.js_videos+memberInfo.jl_videos}}</span>
      &nbsp; &nbsp;&nbsp;&nbsp;立即升级
    </t-button>
  </div>
    <t-tabs v-model="value" @change="handlerChange" style="height: 100%">
      <t-tab-panel :value="item.value" :label="item.label" :destroy-on-hide="false" v-for="(item,key) in tabList" :key="key">
      <div style="padding: 20px;">
        <div style="margin-bottom: 20px; display: flex;justify-content: space-between;align-items: center">

          <t-button theme="primary" @click="openAdd">
            新增视频
          </t-button>
        </div>

        <t-table
            row-key="index"
            :data="data"
            :stripe="true"
            :columns="columns"
            max-height="600px"
            table-layout="auto"
            cell-empty-content="-"
            resizable
            lazy-load
        >
          <template #status="{ row }">
            <span v-if="row.status === 1" style="color: #4ade80">正常</span>
            <span v-else-if="row.status === 2" >生成中</span>
            <span style="color: red" v-else>生成失败:{{row.error_msg}}</span>
          </template>
          <template #pic_url="{ row }">
            <template v-if="row.pic_url">
              <div class="tdesign-demo-image-viewer__base">
                <t-image-viewer :images="[row.pic_url]" >
                  <template #trigger="{ open }">
                    <div class="tdesign-demo-image-viewer__ui-image">
                      <img alt="test"  style="width: 50px;" :src="row.pic_url" class="tdesign-demo-image-viewer__ui-image--img" />
                      <div class="tdesign-demo-image-viewer__ui-image--hover" @click="open">
                        <span><BrowseIcon size="1.4em" /> 预览</span>
                      </div>
                    </div>
                  </template>
                </t-image-viewer>
              </div>
<!--              <img :src="row.pic_url" alt="" style="width: 50px;" />-->
            </template>
            <template v-else>
              <span>暂无预览图</span>
            </template>
          </template>
          <template #operation="{ row }">
              <t-button theme="primary" variant="text" @click="openEdit(row)">重新生成</t-button>
              <t-button theme="danger" variant="text" @click="openDelete(row)" >删除</t-button>

          </template>
        </t-table>

      </div>


      </t-tab-panel>




    </t-tabs>


      <t-dialog
          v-model:visible="isDialogEdit"
          :header="DialogEditHeader"
          width="40%"
          confirmBtn="保存"
          @confirm="save"
      >
        <t-form>
          <t-card bordered>
            <t-form-item label="视频名称"  >
              <t-input  v-model="formData.name"  placeholder="请输入内容" />
            </t-form-item>
            <t-form-item label="平台上的id"  >
              <t-input  v-model="formData.code"  placeholder="请输入内容" />
            </t-form-item>
            <t-form-item label="视频情绪"  >
              <t-radio-group v-model="formData.emotion">
                <t-radio-button :value="emotion" v-for="(emotion, index) in emotions" :key="index" >{{emotion}}</t-radio-button>

              </t-radio-group>
            </t-form-item>
          </t-card>

        </t-form>

  </t-dialog>
  <t-dialog
      v-model:visible="isDialogEditCj"
      :header="DialogEditHeader"
      width="50%"
      confirmBtn="保存"
      @confirm="save"
  >
    <t-form label-align="left">
      <t-card bordered>
        <t-form-item label="视频名称"  >
          <t-input  v-model="formData.name"  placeholder="请输入内容" />
        </t-form-item>
        <t-form-item label="上传MP4文件"  help="Tips：横版或竖版视频，支持MP4格式，360p-4k分辨率 时长30秒-5分钟，文件大小不超过100M"  >
          <t-upload
              v-model="files"
              accept=".mp4"
              ref="uploadRef"
              :headers="uploadHeaders"
              :request-method="requestMethod"
              :abridge-name="[8, 6]"
              theme="file-input"
              :size-limit="{ size: 100, unit: 'MB' }"
              placeholder="请选择需要上传的MP4文件"
              @fail="handleFail"
          ></t-upload>
        </t-form-item>
        <t-form-item label="是否为无声视频" v-if="formData.platform_name === '蝉镜'" >
          <t-radio-group v-model="formData.train_type">
            <t-radio value="0">否</t-radio>
            <t-radio value="1">是</t-radio>

          </t-radio-group>
        </t-form-item>
        <t-form-item label="视频情绪"  >
          <t-radio-group v-model="formData.emotion">
            <t-radio-button :value="emotion" v-for="(emotion, index) in emotions" :key="index" >{{emotion}}</t-radio-button>

          </t-radio-group>
        </t-form-item>
        <p style="color: red;margin-top: 10px;">Tips：视频模板提交即产生费用，所以无法修改，请谨慎选择后再提交</p>

      </t-card>

    </t-form>
  </t-dialog>



  <t-dialog
      v-model:visible="visible3"
      theme="warning"
      header="操作确认"
      body="确然要删除该条数据吗?"
      :cancel-btn="null"
      @confirm="onClickConfirm"
  />

  <t-dialog
      v-model:visible="isDialogDevice"
      header="视频模板加量包"
      width="50%"
      :footer="false"
  >
    <!-- 通过 props 传递参数 -->
    <DeviceView v-if="isDialogDevice" :item="deviceInfo"  />
  </t-dialog>

  <t-loading :loading="loading" text="加载中..." fullscreen />
</template>


<script setup >
import { ref } from 'vue';
import {get,post} from "@/utils/api";
import config from "@/config";
import { MessagePlugin,DialogPlugin  } from 'tdesign-vue-next';
import DeviceView from "@/views/member/DeviceView.vue";
import COS from 'cos-js-sdk-v5';
import md5 from 'js-md5'; // 新增导入

const uploadRef = ref();
const value = ref("小甲鱼");
const isDialogDevice = ref(false)
const tabList = ref([
  //{ label: '蝉镜', value: '蝉镜' },
  // { label: 'HeyGen', value: 'HeyGen' },
  { label: '标准', value: '小甲鱼' },

]);
const deviceInfo = ref({
  type:3,
  orderType:5
})
const emotions = ref(["高兴", "悲伤", "愤怒", "恐惧", "厌恶", "惊讶", "中性"]);
const visible3 = ref(false);
const isDialogEdit = ref(false);
const DialogEditHeader = ref("编辑视频");
const delId = ref(0);



const getVideoList = async () => {
  console.log("getConfigList");
  try {
    const response = await get(config.getVideoList,{
      platform_name:value.value,
      type:2
    }); // Adjust API endpoint as needed
    if (response.status === 200) {
      data.value  = response.data.data;
      console.log("getVideoList",data)
     // data.value = data;
    } else {
      console.error('Failed to fetch feedback data');
    }
  } catch (error) {
    console.error('Error fetching feedback data:', error);
  }


};
getVideoList()

const columns = ref([
  { colKey: 'name', title: '视频名称' },
  { colKey: 'code', title: '视频ID' },
  { colKey: 'status', title: '视频状态'},
  { colKey: 'emotion', title: '视频情绪' },
  { colKey: 'pic_url', title: '预览图' },
  { colKey: 'operation', title: '操作' },
]);

const data = ref([]);

// 打开弹窗并传递参数(扣费逻辑部分)
const openEditCf = (row) => {
  console.log(row);
  if(row.status===3){
    get(config.agenCreateAvatarXiaojiayu,{id:row.id}).then(res => {
      if(res.data.code===1){
        MessagePlugin.success(res.data.info)
        getVideoList()
      }else{
        MessagePlugin.error(res.data.info)
      }
    })
  }else{
    get(config.getPriceRule,{
      stage_tag:"videoTemplate",
      platform:"小甲鱼"
    }).then(res => {
      if(res.data.code===1){
        let price = res.data.data.price_per_unit;
        const confirmDia = DialogPlugin({
          header: '操作确认',
          body: '确认要重新生成吗?重新生成将扣除'+price+'蓝豆!',
          confirmBtn: '确认',
          cancelBtn: '取消',
          onConfirm: ({ e }) => {
            console.log('e: ', e);
            get(config.getBeanBalance,{}).then(res => {
              if(res.data.code===1){
                if(res.data.data.bean_balance>=price){
                  confirmDia.hide();

                  formData.value = row;
                  isDialogEditCj.value = true;
                  DialogEditHeader.value = "重新生成视频";
                }else{
                  MessagePlugin.error('蓝豆余额不足')
                }
              }else{
                MessagePlugin.error(res.data.info)
              }
            })




          },
          onClose: ({ e, trigger }) => {
            console.log('e: ', e);
            console.log('trigger: ', trigger);
            confirmDia.hide();
          },
        });
      }else{
        MessagePlugin.error(res.data.info)
      }
    })
  }


};

const openEdit = (row) => {
  console.log(row);
  if(row.status===3){
    get(config.agenCreateAvatarXiaojiayu,{id:row.id}).then(res => {
      if(res.data.code===1){
        MessagePlugin.success(res.data.info)
        getVideoList()
      }else{
        MessagePlugin.error(res.data.info)
      }
    })
  }else{
    const confirmDia = DialogPlugin({
      header: '操作确认',
      body: '确认要重新生成吗?重新生成将覆盖原视频模板!',
      confirmBtn: '确认',
      cancelBtn: '取消',
      onConfirm: ({ e }) => {
        console.log('e: ', e);
        confirmDia.hide();

        formData.value = row;
        isDialogEditCj.value = true;
        DialogEditHeader.value = "重新生成视频";

      },
      onClose: ({ e, trigger }) => {
        console.log('e: ', e);
        console.log('trigger: ', trigger);
        confirmDia.hide();
      },
    });
  }


};

const openAdd = () => {
  if(memberInfo.value.videos>=memberInfo.value.js_videos+memberInfo.value.jl_videos){
    MessagePlugin.error('当前视频模板已满')
    return false;
  }
  if(value.value==="蝉镜" || value.value==="小甲鱼"){
    isDialogEditCj.value = true;
  }else{
    isDialogEdit.value = true;
  }
  DialogEditHeader.value = "新增视频";
};


// 删除弹窗部分
const openDelete = (row) => {
  visible3.value = true;
  delId.value = row.id;
  console.log('删除的数据',row)
};
const onClickConfirm = async () => {
  try {
    const response = await get(config.delVideo,{id:delId.value}); // Adjust API endpoint as needed
    if (response.status === 200) {
      const data = response.data;
      if(data.code===1){
        MessagePlugin.success(data.info)
      }else{
        MessagePlugin.error(data.info)
      }
      console.log(data)
     // MessagePlugin.success('删除成功')
      visible3.value = false;
      getVideoList()
    } else {
      console.error('Failed to fetch feedback data');
      MessagePlugin.error('删除失败')
    }
  } catch(error) {
    MessagePlugin.error('删除失败')
  }
  visible3.value = false;
 // getTableData();

  console.log('删除成功');
};


const handlerChange = (newValue) => {
  value.value = newValue;
  formData.value.platform_name = newValue;
  getVideoList()

 // getConfig()
};
const formData = ref({
  type:2,
  name:"",
  id:0,
  platform_name:value.value,
  code:"",
  emotion:"",
  file_url:"",
  train_type:0
});

const loading = ref(false);

const save = async () => {
  console.log(formData.value);

  let url = config.saveVideo;
  if(formData.value.platform_name==="蝉镜"){
    console.log("files",files.value)
    if(files.value.length===0){
      MessagePlugin.error('请上传视频文件')
      return
    }
    if(files.value[0].percent<100){
      MessagePlugin.error('请等待视频文件上传完成')
      return
    }
    formData.value.file_url = files.value[0].response.url;
    url = config.createAvatarChanjing;
  }
  if(formData.value.platform_name==="小甲鱼"){
    console.log("files",files.value)
    if(files.value.length===0){
      MessagePlugin.error('请上传视频文件')
      return
    }
    if(files.value[0].percent<100){
      MessagePlugin.error('请等待视频文件上传完成')
      return
    }
    formData.value.file_url = files.value[0].response.url;
    url = config.createAvatarXiaojiayu;
  }




  try {
    loading.value = true;
    const response = await post(url,formData.value); // Adjust API endpoint as needed
    if (response.status === 200) {
      loading.value = false;
      const data = response.data;
      console.log(data)
      if(data.code===0){
        MessagePlugin.error(data.info)
        return;
      }
      MessagePlugin.success('保存成功')
      isDialogEdit.value = false;
      isDialogEditCj.value = false;
      getVideoList();
      formData.value = {
        type:2,
        name:"",
        id:0,
        platform_name:value.value,
        code:"",
        emotion:"",
        file_url:""
      }
    } else {
      loading.value = false;
      console.error('Failed to fetch feedback data');
      MessagePlugin.error('保存失败')
    }
  } catch(error) {
    loading.value = false;
    MessagePlugin.error('保存失败')
  }
};

const isDialogEditCj = ref(false)

const files = ref([]);

const handleFail = ({ file }) => {
  MessagePlugin.error(`文件 ${file.name} 上传失败`);
};

const memberInfo = ref({})
const getMemberInfo = () => {
  get(config.getMemberInfo).then(res => {
    memberInfo.value = res.data.data
    console.log("getMemberInfo", res.data.data)
  })
}
getMemberInfo()

const uploadHeaders = ref({
  token: localStorage.getItem('authToken')
})
const cos = new COS({
  getAuthorization: function (options, callback) {
    // 初始化时不会调用，只有调用 cos 方法（例如 cos.putObject）时才会进入
    // 异步获取临时密钥

    get(config.getTempKeys).then(res => {
      let data = null;
      let credentials = null;
      data = res.data.data
      credentials = data.credentials;
      console.log("getTempKeys", res.data.data)
      if (!data || !credentials) return console.error('credentials invalid');
      callback({
        TmpSecretId: credentials.tmpSecretId,        // 临时密钥的 tmpSecretId
        TmpSecretKey: credentials.tmpSecretKey,      // 临时密钥的 tmpSecretKey
        SecurityToken: credentials.sessionToken, // 临时密钥的 sessionToken
        // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
        StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
        ExpiredTime: data.expiredTime, // 临时密钥失效时间戳，是申请临时密钥时，时间戳加 durationSeconds
        ScopeLimit: true, // 细粒度控制权限需要设为 true，会限制密钥只在相同请求时重复使用
      });
    })

  }
});
const requestMethod = (file) => {
  console.log("requestMethod", file)
  return new Promise((resolve, reject) => {
    // 获取原始文件名后缀
    const fileExtension = file.name.substring(file.name.lastIndexOf('.'));

    // 使用 MD5 哈希 + 原始后缀
    let file_name = md5(file.name);
    let key = `videos/${file_name}${fileExtension}`; // ✅ 保留原始后缀
    cos.putObject({
      Bucket: 'lyzk20050703-1367294934', /* 必须 */
      Region: 'ap-shanghai',    /* 必须 */
      Key: key, // 生成唯一文件名
      Body: file.raw, // 上传文件对象
      onProgress: function (progressData) {           // 非必须
        let percent = progressData.percent*100;
        uploadRef.value.uploadFilePercent({ file, percent });
        console.log("progressData",JSON.stringify(progressData));
      },

    }, function(err, data) {
      if (err) {
        console.error(err);
        MessagePlugin.error('文件上传失败')
        resolve({ status: 'fail'});
      } else {
        console.log("success",data);
        resolve({ status: 'success', response: { url: "http://tdfile.blueant.pro/"+key } });

      }
    });
  });
}


</script>
<style scoped>
.tdesign-demo-image-viewer__ui-image {
  width: 100%;
  height: 100%;
  display: inline-flex;
  position: relative;
  justify-content: center;
  align-items: center;
  border-radius: var(--td-radius-small);
  overflow: hidden;
}

.tdesign-demo-image-viewer__ui-image--hover {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: var(--td-text-color-anti);
  line-height: 22px;
  transition: 0.2s;
}

.tdesign-demo-image-viewer__ui-image:hover .tdesign-demo-image-viewer__ui-image--hover {
  opacity: 1;
  cursor: pointer;
}

.tdesign-demo-image-viewer__ui-image--img {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  cursor: pointer;
  position: absolute;
}

.tdesign-demo-image-viewer__ui-image--footer {
  padding: 0 16px;
  height: 56px;
  width: 100%;
  line-height: 56px;
  font-size: 16px;
  position: absolute;
  bottom: 0;
  color: var(--td-text-color-anti);
  background-image: linear-gradient(0deg, rgba(0, 0, 0, 0.4) 0%, rgba(0, 0, 0, 0) 100%);
  display: flex;
  box-sizing: border-box;
}

.tdesign-demo-image-viewer__ui-image--title {
  flex: 1;
}

.tdesign-demo-popup__reference {
  margin-left: 16px;
}

.tdesign-demo-image-viewer__ui-image--icons .tdesign-demo-icon {
  cursor: pointer;
}

.tdesign-demo-image-viewer__base {
  width: 50px;
  height: 100px;
  margin: 5px;
  border: 1px solid var(--td-bg-color-secondarycontainer);
  border-radius: var(--td-radius-medium);
}
</style>
